﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using KF.DHLModel;
using KF.Common;

namespace KF.DHLBL
{
    /// <summary>
    /// Orders
    /// </summary>
    public partial class OrdersBLL : BLBase
    {
        private readonly KF.DHL.DAL.OrdersDAL dal = new KF.DHL.DAL.OrdersDAL();
        public OrdersBLL()
        { }
        #region  Method

        #region 订单导入、订单录入、订单修改功能
        /// <summary>
        /// 批量导入订单
        /// </summary>
        /// <param name="ordersList"></param>
        /// <returns></returns>
        [Obsolete("批量导入功能已经废弃，建议不再使用")]
        public string ImportOrders(List<Orders> ordersList)
        {
            StringBuilder sbMessage = new StringBuilder();
            List<KF.DHLModel.ZoneInfo> allZoneInfo = new KF.DHL.DAL.ZoneInfo().GetZoneInfo();

            if (allZoneInfo == null)
            {
                sbMessage.AppendLine("导入失败：获取分区信息失败！");
            }
            else
            {
                for (int i = 0; i < ordersList.Count; i++)
                {
                    if (allZoneInfo.Where(o => o.NameS == ordersList[i].CountryCN).Count() != 0)//获取区域信息
                    {
                        ordersList[i].Zone = allZoneInfo.Where(o => o.NameS == ordersList[i].CountryCN).FirstOrDefault().Zone;
                    }
                    else
                    {
                        sbMessage.AppendLine(string.Format("第{0}条数据导入失败，失败原因：未查询到相应的分区信息。", i + 1));
                    }

                    try
                    {
                        dal.Add(ordersList[i]);
                    }
                    catch (System.Exception ex)
                    {
                        sbMessage.AppendLine(string.Format("第{0}条数据导入失败，失败原因：{1}", i + 1, ex.ToString()));
                    }
                }
            }

            LogHelper.DebugHelper.WriteLog(sbMessage.ToString(), LogHelper.ExceptionHelper.ExceptionLevel.Exception);
            return sbMessage.ToString();
        }

        /// <summary>
        /// 导入订单数据
        /// </summary>
        /// <param name="order"></param>
        /// <returns>成功返回 "0" 失败返回 失败原因</returns>
        public string AddOrder(Orders order)
        {
            order.AddTime = DateTime.Now;
            order.AddWho = string.Empty;
            return AddOrEditOrder(order, "ADD");
        }

        /// <summary>
        /// 修改订单数据
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public string EditOrder(Orders order)
        {
            order.EditTime = DateTime.Now;
            order.EditWho = string.Empty;
            return AddOrEditOrder(order, "EDIT");
        }

        /// <summary>
        /// 导入、录入、修改订单数据
        /// </summary>
        /// <param name="order"></param>
        /// <param name="addOrEdit">导入、录入：ADD,修改：EDIT</param>
        /// <returns></returns>
        private string AddOrEditOrder(Orders order, string addOrEdit)
        {
            string message = string.Empty;
            message = ValiDataOrderInfo(order, out message);

            if (!string.IsNullOrEmpty(message))
            {
                LogHelper.DebugHelper.WriteLog(message, LogHelper.ExceptionHelper.ExceptionLevel.Warning);
                return message;
            }

            try
            {
                if (addOrEdit.ToUpper() == "ADD")
                    dal.Add(order);
                else if (addOrEdit.ToUpper() == "EDIT")
                    dal.Update(order);
            }
            catch (System.Exception ex)
            {                
                LogHelper.DebugHelper.WriteLog(ex.ToString(), LogHelper.ExceptionHelper.ExceptionLevel.Exception);
                return string.Format("记录数据库失败，失败原因：{0}", ex.Message);
            }

            return "0";
        }

        /// <summary>
        /// 验证录入、导入的订单信息是否合法，同时修改订单的部分字段为需要的值
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        private string ValiDataOrderInfo(Orders order, out string message)
        {
            message = string.Empty;

            if (!order.VolumeWeight.HasValue)
                order.VolumeWeight = order.RealWeight;

            message = IsExist(order.ID, order.OrderNumber, order.OrderNumberRef);
            if (!string.IsNullOrEmpty(message))
                return "数据验证失败，失败原因：" + message;

            List<KF.DHLModel.ZoneInfo> allZoneInfo = new KF.DHL.DAL.ZoneInfo().GetZoneInfo();
            if (allZoneInfo == null)
                return "数据验证失败，失败原因：获取分区信息失败！";

            if (allZoneInfo.Where(o => o.NameS == order.CountryCN).Count() == 0)//获取区域信息
                return "数据验证失败，失败原因：未查询到对映的分区信息。";

            order.Zone = allZoneInfo.Where(o => o.NameS == order.CountryCN).FirstOrDefault().Zone;

            if (CUSTOMERS_ALL.Where(o => o.Code == order.CustomerCode).Count() == 0)
                return "数据验证失败，失败原因：获取客户信息失败！";

            KF.DHLModel.BaseInfo.Customer customer = CUSTOMERS_ALL.Where(o => o.Code == order.CustomerCode).FirstOrDefault();

            ItemType itemType = ItemType.DOC;
            if (order.ItemType.Value == 1)
                itemType = ItemType.NO;

            try
            {
                order.Price = new KF.DHLBL.Prcing().CalcPrice(new PriceInfo().GetPriceInfo(), order.Zone.Value, order.RealWeight.Value, itemType, customer.Type);
            }
            catch (System.Exception ex)
            {
                LogHelper.DebugHelper.WriteLog(ex.ToString(), LogHelper.ExceptionHelper.ExceptionLevel.Exception);
                return string.Format("数据验证失败，计算价格失败，失败原因：{0}。", ex.Message);
            }

            return message;
        }

        /// <summary>
        /// 判断对映运单号、转单号的数据是否存在，orderNumber（转单号必填且唯一），orderNumberRef（运单号，非必填，唯一）
        /// </summary>
        /// <param name="orderNumber"></param>
        /// <param name="orderNumberRef"></param>
        /// <returns></returns>
        private string IsExist(int OrderID, string orderNumber, string orderNumberRef)
        {
            if (string.IsNullOrEmpty(orderNumber))
                return "转单号不能为空。";
            else if (dal.IsExistOrderNumber(OrderID, orderNumber))
                return "转单号已经存在";

            if (!string.IsNullOrEmpty(orderNumberRef) && dal.IsExistOrderNumberRef(OrderID, orderNumberRef))
                return "运单号已经存在。";

            return string.Empty;
        }

        #endregion

        #region 订单批次信息录入功能
        public string EditOrderBatchInfo(string[] orderNumbers, string batchInfo, string flightInfo, DateTime flihtTime)
        {
            try
            {
                if (dal.EditOrderBatchInfo(orderNumbers, batchInfo, flightInfo, flihtTime))
                    return "0";
                else
                    return "录入批次信息失败，请稍后再试";
            }
            catch (System.Exception ex)
            {
                LogHelper.DebugHelper.WriteLog(ex.ToString(), LogHelper.ExceptionHelper.ExceptionLevel.Exception);
                return ex.Message;
            }
        }

        #endregion

        #region 发运订单功能
        public string ShippingOrders(string[] orderNumbers)
        {
            try
            {
                if (dal.ShippingOrders(orderNumbers))
                    return "0";
                else
                    return "发运订单失败，请稍后再试";
            }
            catch (System.Exception ex)
            {
                LogHelper.DebugHelper.WriteLog(ex.ToString(), LogHelper.ExceptionHelper.ExceptionLevel.Exception);
                return ex.Message;
            }
        }
        #endregion

        #region 自动生成的代码

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Insert(KF.DHLModel.Orders model)
        {
            return dal.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(KF.DHLModel.Orders model)
        {
            return dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int ID)
        {

            return dal.Delete(ID);
        }
        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool DeleteList(string IDlist)
        {
            return dal.DeleteList(IDlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public KF.DHLModel.Orders GetModel(int ID)
        {

            return dal.GetModel(ID);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<KF.DHLModel.Orders> GetModelList(string strWhere)
        {
            DataSet ds = dal.GetList(strWhere);
            return DataTableToList(ds.Tables[0]);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<KF.DHLModel.Orders> DataTableToList(DataTable dt)
        {
            List<KF.DHLModel.Orders> modelList = new List<KF.DHLModel.Orders>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                KF.DHLModel.Orders model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new KF.DHLModel.Orders();
                    if (dt.Rows[n]["ID"] != null && dt.Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(dt.Rows[n]["ID"].ToString());
                    }
                    if (dt.Rows[n]["OrderNumber"] != null && dt.Rows[n]["OrderNumber"].ToString() != "")
                    {
                        model.OrderNumber = dt.Rows[n]["OrderNumber"].ToString();
                    }
                    if (dt.Rows[n]["OrderNumberRef"] != null && dt.Rows[n]["OrderNumberRef"].ToString() != "")
                    {
                        model.OrderNumberRef = dt.Rows[n]["OrderNumberRef"].ToString();
                    }
                    if (dt.Rows[n]["CountryEn"] != null && dt.Rows[n]["CountryEn"].ToString() != "")
                    {
                        model.CountryEn = dt.Rows[n]["CountryEn"].ToString();
                    }
                    if (dt.Rows[n]["CountryCN"] != null && dt.Rows[n]["CountryCN"].ToString() != "")
                    {
                        model.CountryCN = dt.Rows[n]["CountryCN"].ToString();
                    }
                    if (dt.Rows[n]["CountryCode"] != null && dt.Rows[n]["CountryCode"].ToString() != "")
                    {
                        model.CountryCode = dt.Rows[n]["CountryCode"].ToString();
                    }
                    if (dt.Rows[n]["BillingWeight"] != null && dt.Rows[n]["BillingWeight"].ToString() != "")
                    {
                        model.BillingWeight = Convert.ToDouble(dt.Rows[n]["BillingWeight"].ToString());
                    }
                    if (dt.Rows[n]["VolumeWeight"] != null && dt.Rows[n]["VolumeWeight"].ToString() != "")
                    {
                        model.VolumeWeight = Convert.ToDouble(dt.Rows[n]["VolumeWeight"].ToString());
                    }
                    if (dt.Rows[n]["RealWeight"] != null && dt.Rows[n]["RealWeight"].ToString() != "")
                    {
                        model.RealWeight = Convert.ToDouble(dt.Rows[n]["RealWeight"].ToString());
                    }
                    if (dt.Rows[n]["PriceType"] != null && dt.Rows[n]["PriceType"].ToString() != "")
                    {
                        model.PriceType = int.Parse(dt.Rows[n]["PriceType"].ToString());
                    }
                    if (dt.Rows[n]["ItemType"] != null && dt.Rows[n]["ItemType"].ToString() != "")
                    {
                        model.ItemType = int.Parse(dt.Rows[n]["ItemType"].ToString());
                    }
                    if (dt.Rows[n]["Zone"] != null && dt.Rows[n]["Zone"].ToString() != "")
                    {
                        model.Zone = int.Parse(dt.Rows[n]["Zone"].ToString());
                    }
                    if (dt.Rows[n]["Price"] != null && dt.Rows[n]["Price"].ToString() != "")
                    {
                        model.Price = Convert.ToDouble(dt.Rows[n]["Price"].ToString());
                    }
                    if (dt.Rows[n]["AddWho"] != null && dt.Rows[n]["AddWho"].ToString() != "")
                    {
                        model.AddWho = dt.Rows[n]["AddWho"].ToString();
                    }
                    if (dt.Rows[n]["AddTime"] != null && dt.Rows[n]["AddTime"].ToString() != "")
                    {
                        model.AddTime = DateTime.Parse(dt.Rows[n]["AddTime"].ToString());
                    }
                    if (dt.Rows[n]["EditWho"] != null && dt.Rows[n]["EditWho"].ToString() != "")
                    {
                        model.EditWho = dt.Rows[n]["EditWho"].ToString();
                    }
                    if (dt.Rows[n]["EditTime"] != null && dt.Rows[n]["EditTime"].ToString() != "")
                    {
                        model.EditTime = DateTime.Parse(dt.Rows[n]["EditTime"].ToString());
                    }
                    if (dt.Rows[n]["Status"] != null && dt.Rows[n]["Status"].ToString() != "")
                    {
                        model.Status = int.Parse(dt.Rows[n]["Status"].ToString());
                    }
                    if (dt.Rows[n]["Cost"] != null && dt.Rows[n]["Cost"].ToString() != "")
                    {
                        model.Cost = Convert.ToDouble(dt.Rows[n]["Cost"].ToString());
                    }
                    if (dt.Rows[n]["SendTime"] != null && dt.Rows[n]["SendTime"].ToString() != "")
                    {
                        model.SendTime = DateTime.Parse(dt.Rows[n]["SendTime"].ToString());
                    }
                    if (dt.Rows[n]["SendWho"] != null && dt.Rows[n]["SendWho"].ToString() != "")
                    {
                        model.SendWho = dt.Rows[n]["SendWho"].ToString();
                    }
                    if (dt.Rows[n]["Notes"] != null && dt.Rows[n]["Notes"].ToString() != "")
                    {
                        model.Notes = dt.Rows[n]["Notes"].ToString();
                    }
                    if (dt.Rows[n]["CustomerCode"] != null && dt.Rows[n]["CustomerCode"].ToString() != "")
                    {
                        model.CustomerCode = dt.Rows[n]["CustomerCode"].ToString();
                    }
                    if (dt.Rows[n]["BillingPrice"] != null && dt.Rows[n]["BillingPrice"].ToString() != "")
                    {
                        model.BillingPrice = Convert.ToDouble(dt.Rows[n]["BillingPrice"].ToString());
                    }
                    if (dt.Rows[n]["ChannelCode"] != null && dt.Rows[n]["ChannelCode"].ToString() != "")
                    {
                        model.ChannelCode = dt.Rows[n]["ChannelCode"].ToString();
                    }
                    if (dt.Rows[n]["Address"] != null && dt.Rows[n]["Address"].ToString() != "")
                    {
                        model.Address = dt.Rows[n]["Address"].ToString();
                    }
                    if (dt.Rows[n]["Pieces"] != null && dt.Rows[n]["Pieces"].ToString() != "")
                    {
                        model.Pieces = int.Parse(dt.Rows[n]["Pieces"].ToString());
                    }
                    if (dt.Rows[n]["BillWho"] != null && dt.Rows[n]["BillWho"].ToString() != "")
                    {
                        model.BillWho = dt.Rows[n]["BillWho"].ToString();
                    }
                    if (dt.Rows[n]["BillTime"] != null && dt.Rows[n]["BillTime"].ToString() != "")
                    {
                        model.BillTime = DateTime.Parse(dt.Rows[n]["BillTime"].ToString());
                    }
                    if (dt.Rows[n]["OrderTime"] != null && dt.Rows[n]["OrderTime"].ToString() != "")
                    {
                        model.OrderTime = DateTime.Parse(dt.Rows[n]["OrderTime"].ToString());
                    }
                    if (dt.Rows[n]["BatchInfo"] != null && dt.Rows[n]["BatchInfo"].ToString() != "")
                    {
                        model.BatchInfo = dt.Rows[n]["BatchInfo"].ToString();
                    }
                    if (dt.Rows[n]["FlightInfo"] != null && dt.Rows[n]["FlightInfo"].ToString() != "")
                    {
                        model.FlightInfo = dt.Rows[n]["FlightInfo"].ToString();
                    }
                    if (dt.Rows[n]["FlightTime"] != null && dt.Rows[n]["FlightTime"].ToString() != "")
                    {
                        model.FlightTime = DateTime.Parse(dt.Rows[n]["FlightTime"].ToString());
                    }
                    if (dt.Rows[n]["ShippingUser"] != null && dt.Rows[n]["ShippingUser"].ToString() != "")
                    {
                        model.ShippingUser = dt.Rows[n]["ShippingUser"].ToString();
                    }
                    if (dt.Rows[n]["ShippingTime"] != null && dt.Rows[n]["ShippingTime"].ToString() != "")
                    {
                        model.ShippingTime = DateTime.Parse(dt.Rows[n]["ShippingTime"].ToString());
                    }
                    modelList.Add(model);
                }
            }
            return modelList;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }

        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        //public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        //{
        //return dal.GetList(PageSize,PageIndex,strWhere);
        //}
        #endregion

        #endregion  Method
    }
}

